<?php

/*
 * 
 * 深圳活动的控制器
 * 
 * 1. 查看活动参与者排名列表【分页】
 * 
 * 2. 投票
 * 
 * 3. 投票用户的是否粉丝的判断
 * 
 * 4. 分享查看页面
 * 
 * 
 * 
 */


namespace M\Controller;
use Think\Controller;
class AcshenzhenController extends CommonController {
    
    /*
     * 
     * #################### 1 学习食品安全知识 ##################
     *  
     * 
     * 
     * 
     */
    
    
    /*
     * 学习开始页面
     */
    public function learn() {
        
    }
    
    /*
     * 根据题目id反馈题目的信息
     */
    public function ajax_topic_info() {
        $id = I("get.id"); //题库题目的id
        
//        json格式输出结果前端调用
        
    }
    
    
    
     /*
     * 
     * ####################   END ##################
     * 
     * 
     * 
     * 
     */
    
    
    
    /*
     * 
     * #################### 2 考试食品安全知识 ##################
     * 
     * 
     * 
     * 
     */
    
    
    /**
    考试开始
    **/

    /**
     * 考试报名
     */
    public function exam_enter_for(){
        
//        print_r($this->memberinfo);

      if(IS_GET){
        $schoolid = I('get.schoolid');
        $this->assign('schoolid',$schoolid);
        $school_name = M('acshenzhen_school')->where(array('id' => $schoolid))->getField('name');
        $mid = $this->memberinfo['id'];
        $avatar = M('members')->where(array('id' => $mid))->getField('avatar');
        // $mid = 11;
        $DB = M('acshenzhen_member_info');
        $re = $DB->where(array('mid' => $mid))->find();
        if($re){
            if($re['is_exam']==1)
            {
               $this->redirect('M/acshenzhen/exam_answers'); 
            }
            
            $this->assign("member_info", $re);
            $this->assign('avatar',$avatar);
            $this->assign('schoolid',$schoolid);
            $this->assign('school_name',$school_name);
            $this->display();
            
//            $this->redirect('M/acshenzhen/exam_answers');

        }else{
            $this->assign('avatar',$avatar);
            $this->assign('schoolid',$schoolid);
            $this->assign('school_name',$school_name);
            $this->display();
        }
        
      }else if(IS_POST){
          
//        先判断是否有记录
//          有就是更新数据
        $mid = $this->memberinfo['id'];
        $DB = M('acshenzhen_member_info');
        $re = $DB->where(array('mid' => $mid))->find();
        
        if(!empty($re))
        {
            $DB->id = $re['id'];
            $DB->name = trim(I('post.name'));
            
            $DB->save();
            
            
            $this->redirect('M/acshenzhen/exam_answers');
            
            
        }
        else
        {
            $data['mid'] = $this->memberinfo['id'];
            // $data['mid'] = 11;
            $data['school'] = trim(I('post.school'));
            $data['schoolid'] = I('post.schoolid');
            $data['grade'] = "一年级";
            $data['grade_id'] = 1;
            $data['class'] = "一班";
            $data['class_id'] = 1;
            $data['name'] = trim(I('post.name'));
            // print_r($data); die;
            $DB = M('acshenzhen_member_info');
            $re = $DB->data($data)->add();
            if(!empty($re)){

              $this->redirect('M/acshenzhen/exam_answers');
            }else{

              $this->display();
            }
        }
        
          
        
      }
    }



    /**
     * 学习知识
     */
    public function exam_learn(){

      if(IS_GET){
        $schoolid = I('get.schoolid');
        $DB = M('acshenzhen_item_pool');
        $sql = 'select * from fd_acshenzhen_item_pool';
        $list = $DB->query($sql);

        foreach ($list as $key => $value) {
          # code...
          $res['questions'][$key]['question'] = $value['title'];
          $res['questions'][$key]['answers'][] = $value['optionA'];
          $res['questions'][$key]['answers'][] = $value['optionB'];
          $res['questions'][$key]['answers'][] = $value['optionC'];
          $res['questions'][$key]['answers'][] = $value['optionD'];
          $res['questions'][$key]['correctAnswer'] = $value['right_option'];
        }
        $res = json_encode($res);
        
        $this->assign('schoolid',$schoolid);
        $this->assign('res',$res);
        $this->display();
      }
    }



    /**
     * 开始考试
     */
    public function exam_answers(){
      $mid = $this->memberinfo['id'];
      // $mid = 11;
      $re = $this->check_member_isexam($mid);

      if($re){

          $this->redirect('M/acshenzhen/exam_result');

      }else{

          $DB = M('acshenzhen_item_pool');
          $sql = 'select * from fd_acshenzhen_item_pool order by rand() limit 20';
          $list = $DB->query($sql);

          foreach ($list as $key => $value) {
            # code...
            $res['questions'][$key]['question'] = $value['title'];
            $res['questions'][$key]['answers'][] = $value['optionA'];
            $res['questions'][$key]['answers'][] = $value['optionB'];
            $res['questions'][$key]['answers'][] = $value['optionC'];
            $res['questions'][$key]['answers'][] = $value['optionD'];
            $res['questions'][$key]['correctAnswer'] = $value['right_option'];
          }
          $res = json_encode($res);
          $this->assign('res',$res);
          $this->display();
      }
    }

    /**
     * 当考试结束后将用户的考试状态修改为已考试
     */
    public function modify_member_isexam(){
      if(IS_AJAX){

        $mid = $this->memberinfo['id'];
        // $mid = 11;
        $re = M('acshenzhen_member_info')->where(array('mid' => $mid))->data(array('is_exam' => 1))->save();
        if($re){
          echo 1;
        }
      }
    }


    /**
     * 考试结果
     */
    public function exam_result(){

      if(IS_GET){
          
        /*
         * 判断是否有小卫士评选的记录
         * 
         */
          
        
        $DB = M('acshenzhen_member_info');
        $mid = $this->memberinfo['id'];
        // $mid = 11;
        $sql = "select fd_acshenzhen_member_info.name,fd_acshenzhen_member_info.school,fd_members.avatar from fd_acshenzhen_member_info 
        left join fd_members on fd_acshenzhen_member_info.mid=fd_members.id where fd_acshenzhen_member_info.mid=".$mid;
        $list = $DB->query($sql);

        $this->assign('list',$list);
        $this->display();
      }
    }


    /**
     * 检测用户是否考试过
     */
    private function check_member_isexam($mid){
      $map['mid'] = $mid;
      $map['is_exam'] = 1;
      $DB = M('acshenzhen_member_info');

      $re = $DB->where($map)->find();
      return $re;
    }
    
    
     /*
     * 
     * ####################   END ##################
     * 
     * 
     * 
     * 
     */
    
    
    
    /*
     * 
     * #################### 3 食品安全小卫士 ##################
     * 
     * 
     * 
     * 
     */
    
    /*
    * 
    * 苏州活动的控制器
    * 
    * 1. 查看活动参与者排名列表【分页】
    * 
    * 2. 投票
    * 
    * 3. 投票用户的是否粉丝的判断
    * 
    * 4. 分享查看页面
    * 
    * 
    * 
    */
   
    //小卫士排行
    public function xws_rank() {

      if(IS_GET){

          /*
        * 访问量要增加
        */
        $this->_add_view_count();
        
        $DB_1 = M('acshenzhen_xws_vote');
        $DB_2 = M('acshenzhen_xws_vote_log');
        
        $member_num = $DB_1->count();
        $vote_num = $DB_2->count();
        $pv_num = M("vote_setting")->where(array("keyword"=>"sz_xws_pv"))->getField("keyvalue");
        
        
        $search_keywords = I('get.search_keywords');
        if(!empty($search_keywords)){

            if(is_numeric($search_keywords)){

            $sql = "select fd_acshenzhen_xws_vote.*,fd_acshenzhen_member_info.name as name from fd_acshenzhen_xws_vote left join
               fd_acshenzhen_member_info on fd_acshenzhen_xws_vote.mid=fd_acshenzhen_member_info.mid where 
               fd_acshenzhen_xws_vote.id=".$search_keywords." ORDER BY fd_acshenzhen_xws_vote.vote_num desc,fd_acshenzhen_xws_vote.ctime";
            }else{
               $sql = "select fd_acshenzhen_xws_vote.*,fd_acshenzhen_member_info.name as name from fd_acshenzhen_xws_vote left join
                   fd_acshenzhen_member_info on fd_acshenzhen_xws_vote.mid=fd_acshenzhen_member_info.mid where 
                   fd_acshenzhen_member_info.name like'%".$search_keywords."%'"." ORDER BY fd_acshenzhen_xws_vote.vote_num desc,fd_acshenzhen_xws_vote.ctime";
            }
            
//            print_r($sql);
            $list = $DB_1->query($sql);
        }else{
            
            
            /**
            数据分页显示开始
            **/
            $count      = $DB_1->count();// 查询满足要求的总记录数
            $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $show       = $Page->show();// 分页显示输出
            // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
            $sql = "select fd_acshenzhen_xws_vote.*,fd_acshenzhen_member_info.name as name from fd_acshenzhen_xws_vote left join
                   fd_acshenzhen_member_info on fd_acshenzhen_xws_vote.mid=fd_acshenzhen_member_info.mid"." ORDER BY fd_acshenzhen_xws_vote.vote_num desc,fd_acshenzhen_xws_vote.ctime ".
                   " limit ".$Page->firstRow.",".$Page->listRows;
            $list = $DB_1->query($sql);
            /**
            数据分页结束
            **/
        }
        foreach ($list as $key => $value) {
          # code...
//          $list[$key]['vote_num'] = $DB_2->where(array('wsid' => $value['id']))->count();
          $list[$key]['rank'] = $Page->firstRow+$key+1;
          
        }
        // print_r($list); die;

        $this->assign('member_num',$member_num);
        $this->assign('vote_num',$vote_num);
        $this->assign('pv_num', $pv_num);
        $this->assign('show',$show);
        $this->assign('list',$list);
        $this->assign('page_title', "食品安全小卫士评选");
        $this->display();
      }
    }
    
    
    /*
     * 发起投票
     * 
     * 1. 微信端发起
     * 2. 采用微信自带的图片上传控件
     * 3. 
     * 
     */
    public function xws_vote_create() {
//        echo "ddd";
//        exit();
        
        
        if(IS_POST)
        {
            /*
             * 提交来的姓名，宣言，口号等等
             * 
             */
//          
            $mid = $this->memberinfo['id'];
            $DB = M("acshenzhen_xws_vote");
            $map['mid']=$mid;
            $res = $DB->where($map)->find();
            
            if(!empty($res))
            {
                redirect(U('xws_vote_detail_myself',array('id'=>$res['id'])));
            }
            
            
            $wx_media_ids = I('post.wx_media_ids');
            
            /*
             * 根据media id 来下载图片到本地数据库
             */
            if(!empty($wx_media_ids))
            {
                $accessToken = $this->accessToken;
                    
                $wx_media_arr = json_decode(htmlspecialchars_decode($wx_media_ids),true);
                $sampleids = "";
                $targetName_arr = array();
                foreach ($wx_media_arr as $key => $value) {
                    $filename = date('YmdHis').$this->random_code().'.jpg';
                    $targetName = "./Uploads/fundings/wx_media/".$filename;
                    
                    array_push($targetName_arr, $targetName);
                    
                    $ch = curl_init("http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=$accessToken&media_id=$value");
                    $fp = fopen($targetName, 'wb');
                    curl_setopt($ch, CURLOPT_FILE, $fp);
                    curl_setopt($ch, CURLOPT_HEADER, 0);
                    curl_exec($ch);
                    curl_close($ch);
                    fclose($fp);
                    
                    /*
                     * 插入记录
                     * 1. 插入到 image 表 并得到返回的id写入 sampleid
                     */
                   $id[$key] = $this->insert_image(substr($targetName, 1));
                   $sampleids .=$id[$key].",";
                    
                    
                }
            
                /*
                * 处理第一张图片就是默认的图片
                */
//               print_r($targetName_arr);
//               exit();
               if(!empty($targetName_arr))
               {
                   $data['thumb']=  substr($targetName_arr[0], 1);
               }
            }
            
            $member_info = M("acshenzhen_member_info")->where(array('mid'=>  $this->memberinfo['id']))->find();
            
            
//            $data['thumb'] = "/Uploads/fundings/show/2016-02-29/56d3fd6c79fee.jpeg";  //临时
            $data['ctime']=I("server.REQUEST_TIME");
            $data['slogan'] = I("post.slogan");
            $data['vote_name']=  I("post.vote_name");
            $data['mid']=$this->memberinfo['id'];
            $data['schoolid']=$member_info['schoolid'];
            $data['grade_id']=$member_info['grade_id'];
            $data['class_id']=$member_info['class_id'];
            
            $DB = M("acshenzhen_xws_vote");
            $id = $DB->add($data);
            
            if($id)
            {
                /*
                 * 插入临时二维码关联表
                 */
                $t_data['type']=3;
                $t_data['for_id']=$id;
                $t_data['ctime']=I("server.REQUEST_TIME");
                
                $t_id = M("wx_temporary_qr_code_relationship")->add($t_data);
                
//                print_r(M("temporary_qr_code_relationship")->getLastSql());
                
                
//                保存二维码
                
                
                $qrcode_url = $this->create_qrcode($t_id);
                $DB->id = $id;
                $DB->qrcode_url = $qrcode_url;
                $DB->save();
                
                redirect(U('xws_vote_detail_myself',array('id'=>$id)));
            }
            else
            {
                $this->error("报名错误");
            }
        }
        else
        {
            
            /*
        * 访问量要增加
        */
        $this->_add_view_count();
        
        
        /*
         * 判断，用户需要关注并且报名考试通过了才可以发起
         * 
         */
        $mid = $this->memberinfo['id'];
//        判断是否关注
        $isfan = $this->_chk_if_fan($mid);
        
        if(!$isfan)
        {
            redirect(U('xws_foucuspage')); 
        }
        
        
//        判断是否考试通过
        
            $member_info = M("acshenzhen_member_info")->where(array('mid'=>  $this->memberinfo['id']))->find();
            
            if($member_info['is_exam']==0 || empty($member_info))
            {
                redirect(U('exam_enter_for',array('schoolid'=>1))); 
            }
        
        
        
        
            $DB_1 = M('acshenzhen_xws_vote');
            $DB_2 = M('acshenzhen_xws_vote_log');

            $member_num = $DB_1->count();
            $vote_num = $DB_2->count();
            $pv_num = M("vote_setting")->where(array("keyword"=>"sz_xws_pv"))->getField("keyvalue");
            /*
             * 判断是否有记录了
             */
            
            $DB = M("acshenzhen_xws_vote");
            $map['mid']=$mid;
            $res = $DB->where($map)->find();
            
            if(!empty($res))
            {
                redirect(U('xws_vote_detail_myself',array('id'=>$res['id'])));
            }
            
            /*
             * 获取用户的信息
             * 
             */
//            $mid = $this->memberinfo['id'];
//            $username = $this->memberinfo['username'];
            
//            $this->assign("memberinfo", $this->memberinfo);
            
            $this->assign("memberinfo", $member_info);
//            print_r($this->memberinfo);
            
            $this->assign('member_num',$member_num);
            $this->assign('vote_num',$vote_num);
            $this->assign('pv_num', $pv_num);
            $this->assign('page_title', "食品安全小卫士评选");
            $this->display();
        }
    }
    
    
    /*
     * xws_foucuspage
     * 小卫士微信公众号关注页面
     * 
     */
    
    public function xws_foucuspage() {
        $this->display();
    }
    
    //上传图片
    public function uploadimg() {
        $from = I('get.from');
        if(empty($from))
        {
            $from =0;

        }
        $this->assign('from', $from);

        $this->display();
    }
    
    /*
     * 插入图片到fd_fundings_image表
     */
    private function insert_image($img_url)
    {
        $DB = M("fundings_image");
        $data['img_url']=$img_url;
        
        $id = $DB->add($data);
        
        return $id;
        
    }
    

    //详情
    public function xws_vote_detail() {
        if(IS_GET){

            $id = I('get.id');
            $DB_1 = M('acshenzhen_xws_vote');
            $DB_2 = M('acshenzhen_xws_vote_log');
            $sql = "select fd_acshenzhen_xws_vote.*,fd_acshenzhen_member_info.name as name from fd_acshenzhen_xws_vote left join
               fd_acshenzhen_member_info on fd_acshenzhen_xws_vote.mid=fd_acshenzhen_member_info.mid where 
               fd_acshenzhen_xws_vote.id=".$id;
            
            $list = $DB_1->query($sql);
            foreach ($list as $key => $value) {
              # code...
//              $list[$key]['vote_num'] = $DB_2->where(array('wsid' => $value['id']))->count();
            }
            // print_r($list); die;
            $this->assign('list',$list);
            $this->assign('mid', $this->memberinfo['id']);
            
            $this->assign('page_title', "食品安全小卫士评选");
            $this->display();
        }
    }
    
    
    public function xws_vote_detail_myself() {
        if(IS_GET){

            $id = I('get.id');
            $DB_1 = M('acshenzhen_xws_vote');
            $DB_2 = M('acshenzhen_xws_vote_log');
            $sql = "select fd_acshenzhen_xws_vote.*,fd_acshenzhen_member_info.name as name from fd_acshenzhen_xws_vote left join
               fd_acshenzhen_member_info on fd_acshenzhen_xws_vote.mid=fd_acshenzhen_member_info.mid where 
               fd_acshenzhen_xws_vote.id=".$id;
            
            $list = $DB_1->query($sql);
            foreach ($list as $key => $value) {
              # code...
//              $list[$key]['vote_num'] = $DB_2->where(array('wsid' => $value['id']))->count();
            }
            // print_r($list); die;
            $this->assign('list',$list);
            $this->assign('mid', $this->memberinfo['id']);
            
            $this->assign('page_title', "食品安全小卫士评选");
            $this->display();
        }
    }
    
    
    
   
   //小卫士投票
    public function xws_vote_it() {
       /*
        * ##Rule: 一人一天只能投票一次
        * 
        */  
      if(IS_AJAX){

        $mid = $this->memberinfo['id'];
        $id = I('post.id');
        $isfan = $this->_chk_if_fan($mid);

        if($isfan){
            //判断用户是否已投过票
            $re = $this->_chk_is_vote($mid,$id);
            // echo $re; die;
            if($re){
              //已投票
                echo 2;
//              echo json_encode(2);
            }else{
                $data['wsid'] = $id;
                $data['openid'] = M('members')->where(array('id' => $mid))->getField('wxopenid');
                $data['ctime'] = I('server.REQUEST_TIME');
                $DB = M('acshenzhen_xws_vote_log');

                $result = $DB->data($data)->add();
                if($result){
                    $this->_add_vote_num($id);
                    echo 1;
//                  echo json_encode(1);
                }
            }
        }else{

          //未关注
            echo 3;
//          echo json_encode(3);
        }
      }
       
   }
   
   /*
    * 小卫士详情
    */
   public function xws_instruction() {
       $this->display();
   }
   
   /*
    * 判断是否是粉丝
    */
   private function _chk_if_fan($mid) {
       //根据 mid 获取到 Unionid
       //然后判断 unionid 是否是 两个微信号的粉丝
      $openid = M('members')->where(array('id' => $mid))->getField('wxopenid');
      // echo $openid; die;
      $DB = M("members_subscribe_records");
      $map['openid'] = $openid;
      $map['issubscribe']=1;
      $res = $DB->where($map)->find();
      if(empty($res))
      {
          return FALSE;
      }
      else
      {
         return $res; 
      }
      
   }

   /**
    * 检查是否投过票
    */
   private function _chk_is_vote($mid,$id){

       /*
        * 先判断是否为自己投给自己
        */
       
       $res_vote_info = M("acshenzhen_xws_vote")->find($id);
       
       if($res_vote_info['mid']==$mid)
       {
           return TRUE;
       }
       else
       {
           $openid = M('members')->where(array('id' => $mid))->getField('wxopenid');

            $DB = M('acshenzhen_xws_vote_log');
            $map['openid'] = $openid;
            $todaytime = strtotime(date('Y-m-d',time()));
            $map['ctime'] = array('gt',$todaytime);
            $res = $DB->where($map)->find();
            return $res;
       }
       
       
      
   }
   
   /*
    * 获取投票选项的投票数目
    */
   private function _get_wxs_vote_count($id)
   {
       
   }
   
   /*
    * 计算排名
    */
   private function _cal_rank()
   {
       
   }
   
   /*
    * 访问量要增加
    */
   private function _add_view_count()
   {
       M("vote_setting")->where("id=3")->setInc("keyvalue");
   }
   
   /*
    * 添加投票数量
    */
   private function _add_vote_num($id)
   {
       M("acshenzhen_xws_vote")->where("id=$id")->setInc("vote_num");
   }
   
   /*
     * 生成关注的临时二维码
     * 通过 vid（发起投票的选项的id 来生成临时二维码参数，因为临时二维码只支持 数字 ）
     */
    private function create_qrcode($vid) {
        $accessToken = $this->getAccessToken();
        $wxsdk = new \Com\WechatAuth(C('appid'), C('appsecret'),$accessToken);
        
        $qrcode_res = $wxsdk->qrcodeCreate($vid,"",2592000);
//         print_r($qrcode_res); die;
        if(!isset($qrcode_res['errcode'])){

            //不存在 errcode 则说明得到正常返回数据
            $qrcode_img = $this->get_qrcode_by_ticket($qrcode_res['ticket']);
//            print_r($qrcode_img);
            
            return $qrcode_img;
//            $res['qrcode_img'] = $qrcode_img;
//            $res['scene_str'] = $scene_str;
            
        }
        else
        {
            return FALSE;
        }
        
        
    }
    
    /*
     * 保存access_token 的最新状态
     * 
     */
    private function getAccessToken() {

        $jssdk = new \Com\JSSDK(C('appid'), C('appsecret'));
        $access_token = $jssdk->returnAccessToken();
        return $access_token;
    }
    
    /**
     * 通过ticket获取二维码图片
     * 
     */
    private function get_qrcode_by_ticket($ticket){


        $ticket = urlencode($ticket);

        $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket;

        return $url;
    }







   
   /*
    * ################## 你投票我检查活动 ##################
    */
   
   
   /*
    * 投票列表
    */
   
   public function like_product_list() {

       if(IS_GET){

          $DB = M('acshenzhen_product');
          $DB_log = M('acshenzhen_vote_log');
          /**
            数据分页显示开始
            **/
          $map_1['ishidden']=0;
          $map_1['type']=0;
          $map_1['vote_num']=array("LT",300);
          
            $count      = $DB->where($map_1)->count();// 查询满足要求的总记录数
            $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $show       = $Page->show();// 分页显示输出
            // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
            $sql = "select fd_acshenzhen_product.* from fd_acshenzhen_product where ishidden=0 and type=0 and vote_num <300 order by vote_num desc"." limit ".$Page->firstRow.",".$Page->listRows;
            $list = $DB->query($sql);
            /**
            数据分页结束
            **/
          $page_count = ($Page->firstRow)/10;
          foreach ($list as $key => $value) {
            # code...
            // $list[$key]['vote_num'] = $DB_log->where(array('pid' => $value['id']))->count();
            $list[$key]['rank'] = $page_count * 10 + $key + 1;
          }
          /**
           * 循环判断用户是否投票过
           */
          $todaytime = strtotime(date('Y-m-d',time()));
          $map['ctime'] = array('gt',$todaytime);
          $map['mid'] = $this->memberinfo['id'];
          // $map['mid'] = 11;
          foreach ($list as $key => $value) {
            # code...
            $map['pid'] = $value['id'];

            $re = $DB_log->where($map)->find();
            if($re){
              $list[$key]['is_vote'] = 1;
            }else{
              $list[$key]['is_vote'] = 0;
            }
          }
          // print_r($list); die;
          $this->assign('list',$list);

          $this->display();
       }
   }
   
   /*
    * 送检产品列表
    */
   public function like_product_success_list() {
      if(IS_GET){

          $DB = M('acshenzhen_product');
          $map_1['ishidden']=0;
          $map_1['type']=0;
          $map_1['vote_num']=array("EGT",300);
          /**
            数据分页显示开始
            **/
            $count      = $DB->where($map_1)->count();// 查询满足要求的总记录数
            $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $show       = $Page->show();// 分页显示输出
            // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
            $sql = "select fd_acshenzhen_product.* from fd_acshenzhen_product where ishidden=0 and type=1 and vote_num >=300 "." limit ".$Page->firstRow.",".$Page->listRows;
            $list = $DB->query($sql);
            /**
            数据分页结束
            **/
            // print_r($list); die;
            $this->assign('page',$show);// 赋值分页输出
            $this->assign('list',$list);
            $this->display();
      }
   }
   
   
   /*
    * 上传产品
    */
   public function like_product_diy_submit() {
      $this->display(); 
       
   }
   
   
   /*
    * 活动说明 
    */
   public function like_notice() {
       $this->display();
   }
   
   
   /**
    * ajax投票 每个用户每个项目只投一票
    */
   public function add_one_vote(){
      if(IS_AJAX){

          $DB = M('acshenzhen_vote_log');
          $pid = I('post.pid');
          $mid = $this->memberinfo['mid'];
          // $mid = 11;
          $ctime = I('server.REQUEST_TIME');
          $DB->data(array('pid' => $pid,'mid' => $mid,'ctime' => $ctime))->add();
          $re = M('acshenzhen_product')->where(array('id' => $pid))->setInc('vote_num',1);
          if(!empty($re)){
              echo 1;
          }
      }
   }
   
   /*
    * 访问量要增加
    */
//   private function _add_view_count()
//   {
//       M("vote_setting")->where("id=2")->setInc("keyvalue");
//   }
   
   /*
     * 计算
     * * 参与人数
        * 投票数量
        * 浏览数量
     */
    private function _get_statistics_data()
    {
        $data['join_count']= M("acshenzhen_xws_vote")->count();
        $data['vote_count']=M("acshenzhen_xws_vote_log")->count();
        $data['view_count'] = M("vote_setting")->where(array('keyword'=>'sz_xws_pv'))->getField('keyvalue');
        
        return $data;
    }

   /**
    * 查询用户是否已经给该项目投过票
    */
   
   /*
     * 
     * ####################   END ##################
     * 
     * 
     * 
     * 
     */
   







   /**
      你投票我检测app页面
   **/
   
   /*
    * 投票列表
    */
   public function like_product() {
       $member = $this->memberinfo;
       $mid = $member['id'];
       
       redirect(U("like_product_list_app",array('mid'=>$mid)));
   }


   public function like_product_list_app() {

       if(IS_GET){

          $DB = M('acshenzhen_product');
          $DB_log = M('acshenzhen_vote_log');
          
          $map_1['ishidden']=0;
          $map_1['type']=0;
          $map_1['vote_num']=array("LT",300);
          /**
            数据分页显示开始
            **/
            $count      = $DB->where($map_1)->count();// 查询满足要求的总记录数
            $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $show       = $Page->show();// 分页显示输出
            // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
            $sql = "select fd_acshenzhen_product.* from fd_acshenzhen_product where ishidden=0 and type=0 and vote_num <300 order by vote_num desc"." limit ".$Page->firstRow.",".$Page->listRows;
            $list = $DB->query($sql);
            /**
            数据分页结束
            **/
          $page_count = ($Page->firstRow)/10;
          foreach ($list as $key => $value) {
            # code...
            // $list[$key]['vote_num'] = $DB_log->where(array('pid' => $value['id']))->count();
            $list[$key]['rank'] = $page_count * 10 + $key + 1;
          }
          /**
           * 循环判断用户是否投票过
           */
          $todaytime = strtotime(date('Y-m-d',time()));
          $map['ctime'] = array('gt',$todaytime);
          // $map['mid'] = $this->memberinfo['id'];
          $map['mid'] = I('get.mid');
          foreach ($list as $key => $value) {
            # code...
            $map['pid'] = $value['id'];

            $re = $DB_log->where($map)->find();
            if($re){
              $list[$key]['is_vote'] = 1;
            }else{
              $list[$key]['is_vote'] = 0;
            }
          }
          // print_r($list);die;
          $this->assign('page',$show);// 赋值分页输出
          $this->assign('list',$list);
          $this->assign('mid',$map['mid']);
          $this->display();
       }
   }
   
   /*
    * 送检产品列表
    */
   public function like_product_success_list_app() {
      if(IS_GET){

          $DB = M('acshenzhen_product');
          $mid = I('get.mid');
          
           $map_1['ishidden']=0;
          $map_1['type']=1;
          $map_1['vote_num']=array("EGT",300);
          /**
            数据分页显示开始
            **/
            $count      = $DB->where($map_1)->count();// 查询满足要求的总记录数
            $Page       = new \Think\Page($count,10);// 实例化分页类 传入总记录数和每页显示的记录数(25)
            $show       = $Page->show();// 分页显示输出
            // 进行分页数据查询 注意limit方法的参数要使用Page类的属性
            $sql = "select fd_acshenzhen_product.* from fd_acshenzhen_product where ishidden=0 and type=1 and vote_num >= 300 "." limit ".$Page->firstRow.",".$Page->listRows;
            $list = $DB->query($sql);
            /**
            数据分页结束
            **/
            // print_r($list); die;
            $this->assign('list',$list);
            $this->assign('mid',$mid);
            $this->display();
      }
   }
   
   
   /*
    * 上传产品
    */
   public function like_product_diy_submit_app() {
    
    if(IS_POST)
    {
        
        if(!empty($_FILES['image']['tmp_name']))
        {
            $upload = new \Think\Upload();// 实例化上传类
            $upload->maxSize   =     31457280 ;// 设置附件上传大小
            $upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
            $upload->rootPath  =      'Public/'; // 设置附件上传目录
            $upload->savePath  =      'uploads/'; // 设置附件上传目录
            // 上传文件 
            $info   =   $upload->uploadOne($_FILES['image']);

            if(!$info) {// 上传错误提示错误信息
                $this->error($upload->getError());
            } 
            
            $data['img']="/".$upload->rootPath.$info['savepath'].$info['savename'];
            $thumb = $this->img_thumb2($data['img']);
            $data['img'] = $thumb;
            
        }

        $data['name']=I("post.productname");
        
        $data['ctime']=I("server.REQUEST_TIME");
        $data['mid']= I("post.mid");
        
        $id = M("acshenzhen_product")->add($data);
        
        if($id)
        {
            redirect(U('like_product_list_app',array('mid'=>I("post.mid"))));
        }
        else {
           
        }
        
        
    }
    else
    {
         $mid = I('get.mid');
         $this->assign('mid',$mid);
         $this->display();  
    }
     
       
   }
   
   private function img_thumb2($img_url)
	{
		$image = new \Think\Image(); 
		$img_url = './'.$img_url;
		$image->open("$img_url");
		$img_name=$this->img_name().'.jpg';
		$re_small_url=__ROOT__.'/'.'Uploads'.'/'.'adv'.'/'.'change_small'.'/'.$img_name;
		$small_url='./'.'Uploads'.'/'.'adv'.'/'.'change_small'.'/'.$img_name;
		// echo $small_url; die;
		// 生成一个居中裁剪为30*30的缩略图并保存
		$image->thumb(500, 500,\Think\Image::IMAGE_THUMB_SCALE)->save($small_url);
		return $re_small_url;
	}
        
        //生成随机图像名称
	private function img_name()
	{
		$time=I('server.REQUEST_TIME');
		return $time.str_pad(mt_rand(1, 99999), 5, '0', STR_PAD_LEFT);
	}
   
   
   /*
    * 活动说明 
    */
   public function like_notice_app() {

      $mid = I('get.mid');
      $this->assign('mid',$mid);
      $this->display();
   }
   
   
   /**
    * ajax投票 每个用户每个项目只投一票
    */
   public function add_one_vote_app(){
      if(IS_AJAX){

          $DB = M('acshenzhen_vote_log');
          $pid = I('post.pid');
          // $mid = $this->memberinfo['mid'];
          $mid = I('post.mid');
          $ctime = I('server.REQUEST_TIME');
          $map['pid'] = $pid;
          $map['mid'] = $mid;
          $todaytime = strtotime(date('Y-m-d',time()));
          $map['ctime'] = array('gt',$todaytime);
          $is_vote = $DB->where($map)->find();
          //如果已经投过票
          if($is_vote){

              $re = 0;
          }else{

              $DB->data(array('pid' => $pid,'mid' => $mid,'ctime' => $ctime))->add();
              $re = M('acshenzhen_product')->where(array('id' => $pid))->setInc('vote_num',1);
          }
          /*
           * 判断是否满标了
           */
          $db_2 = M('acshenzhen_product');
          $res = M('acshenzhen_product')->find($pid);
          if($res['vote_num']>=300)
          {
              $db_2->id = $pid;
              $db_2->type=1;
              $db_2->save();
              print_r($res);
          }
          
          if(!empty($re)){
            
              echo 1;
          }else{

              echo 0;
          }
      }
   }
   
   /*
     * 
     * ####################   END ##################
     * 
     * 
     * 
     * 
     */
    





   /*
     * 
     * ####################   END ##################
     * 
     * 
     * 
     * 
     */
   
    
    /*
     * 摇一摇抽奖
     * 
     * 获取中奖的资料
     * 判断是否有中奖
     * 
     */
    public function prize_yaoyiyao() {
        
        $mid = $this->memberinfo['id'];
        
        $DB = M("acshenzhen_member_info");
        $map['mid']=$mid;
        $res=  $DB->where($map)->find();
        
        if(!empty($res))
        {
            //有记录
            $this->assign('lefttime', $res['prize_left_count']);
        }
        else
        {
            //没有记录
            $this->assign('lefttime', 0);
        }
        
        $this->assign("mid", $mid);
        $this->display();
    }
    
    
    /*
     * 
     * 中奖结果
     */
    public function prize_result() {
         //判断环境
        if(!C('debug'))
        {
            $site_domain = C('product_domain');
        }
        else
        {
            $site_domain = C('development_domain');
        }
        
        $mid = $this->memberinfo['id'];
        
        $map['mid']=$mid;
        $map['pid']=array("gt",0);
        $DB = M("acshenzhen_prize_record");
        
        $res = $DB->where($map)->find();
        
        if(!empty($res))
        {
//            有获奖记录
            $prize_content = M("acshenzhen_prize_repository")->find($res['pid']);
            $data['prize_thumb'] = $site_domain.$prize_content['img'];
            $data['is_prize']=1;
            
        }
        else
        {
//            没有获奖
            $data['prize_thumb'] = $site_domain.'/Public/acsuzhou/images/win.png';
            $data['is_prize']=0;
            
        }
        
        $this->assign('result', $data);
        
        $this->display();
    }
    
    /*
     * 计算是否中奖
     * 
     * 通过提交来的 mid 来计算中奖的情况
     */
    public function get_prize() {
        //判断环境
        if(!C('debug'))
        {
            $site_domain = C('product_domain');
        }
        else
        {
            $site_domain = C('development_domain');
        }
        
        $mid = $this->memberinfo['id'];
        
        
            /*
             * 获取个人资料，得到是几年级的学生，查看相同班级的同学，礼品数量是否兑换完了
             *              1. 已经换完，就提示没中奖，减掉次数
             *              2. 没有换完，计算中的概率，看结果
             * 减去中奖次数
             */
            
            $DB_member_info = M("acshenzhen_member_info");
            $member_info = $DB_member_info->where(array('mid'=>$mid))->find();
            
            
            if($member_info['is_prize']==1)
            {
                //中奖过的情况，直接提示不中奖了
                $result['is_prize']=0;
                $result['prize_msg']="没中奖1";
                if($member_info['prize_left_count']>0)
                {
                    $result['prize_left_count']=$member_info['prize_left_count']-1;
                    $this->_reduce_prize_count($mid);
                    
                    //增加不中奖的记录
                        $this->_add_unwin_prize_record($member_info);
                }
                else
                {
                    $result['prize_left_count']=0;
                }
                
                $this->json_output($result);  
                exit();
                
            }
            
            
            if($member_info['prize_left_count']==0)
            {
                // 没抽奖的次数的情况
                $result['is_prize']=0;
                $result['prize_msg']="没中奖2";
                $result['prize_left_count']=0;
            }
            else
            {
                //还有抽奖次数的情况
                $randmom = rand(0,1);
                if($randmom==1)
                {
                    //几率中奖，还要判断是否还剩余奖品
                    $DB_prize_record = M("acshenzhen_prize_record");
                    $map_prize_record['schoolid']=$member_info['schoolid'];
                    $map_prize_record['grade_id']=$member_info['grade_id'];
                    $map_prize_record['class_id']=$member_info['class_id'];
                    $map_prize_record['pid']=array("gt",0);
                    
                    $res_prize_record = $DB_prize_record->where($map_prize_record)->select();
                    
                    if(!empty($res_prize_record))
                    {
                        $tmp_prize_got = "(";
                        foreach ($res_prize_record as $key => $value) {
    //                        array_push($tmp_prize_got, $value['pid']);
                            $tmp_prize_got .=$value['pid'].",";
                        }
                        $tmp_prize_got = substr($tmp_prize_got, 0,-1);
                        $tmp_prize_got .=")";
                    }
                    
                    
                    $res_prize_record_count  = count($res_prize_record);
                    
                    if($res_prize_record_count<10)
                    {
//                        还有中奖的机会
                        
                        $DB_acshenzhen_prize = M("acshenzhen_prize");
//                        $map_acshenzhen_prize['grade_id'] = 
                            
                            /*
                             * 测试着，那个奖品的关联关系还是单独算
                             * 
                             * 找出现在中奖的奖品有什么
                             * 
                             * 
                             */
                        
                            $prize_current_map['grade_id']=$member_info['grade_id'];
                            
                            $prize_current_res = $DB_acshenzhen_prize->where($prize_current_map)->select();
                            
//                             echo $DB_acshenzhen_prize->getLastSql();
//                             echo "<br/>";
                             
                            $tmp_prize_parent=array();
                            
                            foreach ($prize_current_res as $key => $value) {
                                array_push($tmp_prize_parent, $value['id']);
                            }
                            
//                            print_r($tmp_prize_got);
                            
//                            print_r($tmp_prize_parent);
                            $map_prize_children['parent_id']=array("in",$tmp_prize_parent);
                            if(!empty($res_prize_record))
                            {
                                $map_prize_children['id']=array("exp","not in $tmp_prize_got");
                            }
                            
//                            $map_prize_children['_logic']="OR";
                            
                            
                            $res_prize_children = M("acshenzhen_prize_repository")->where($map_prize_children)->select();
//                            
//                            echo M("acshenzhen_prize_repository")->getLastSql();
//                            print_r($res_prize_children);
//                            
                            $current_get_prize = $res_prize_children[array_rand($res_prize_children,1)];
                            
//                            print_r($current_get_prize);
//                            
//                            exit();
                            
                            $result['is_prize']=1;
                            $result['prize_msg']="恭喜中奖1";
                            $result['prize_left_count']=$member_info['prize_left_count']-1;
                            $result['prize_thumb']=$site_domain.$current_get_prize['img'];
                            
                            
                            /*
                             * 写入中奖记录
                             */
                            $DB_data_get_prize = M("acshenzhen_prize_record");
                            $data_get_prize['mid']=$mid;
                            $data_get_prize['pid']=$current_get_prize['id'];
                            $data_get_prize['ctime']=I("server.REQUEST_TIME");
                            $data_get_prize['schoolid']=$member_info['schoolid'];
                            $data_get_prize['grade_id']=$member_info['grade_id'];
                            $data_get_prize['class_id']=$member_info['class_id'];
                            
                            $id_data_get_prize = $DB_data_get_prize->add($data_get_prize);
                            
                            if($id_data_get_prize)
                            {
                                $DB_member_info->id = $member_info['id'];
                                $DB_member_info->is_prize = 1;
                                $DB_member_info->save();  
                            }
                            
                            
                            
                            /*
                             * 测试着，那个奖品的关联关系还是单独算
                             */
                        
                        //抽奖次数减一
                        $this->_reduce_prize_count($mid);
                    }
                    else
                    {
//                        没有奖品了
                        $result['is_prize']=0;
                        $result['prize_msg']="没中奖3";
                        $result['prize_left_count']=$member_info['prize_left_count']-1;
                        
                        //抽奖次数减一
                        $this->_reduce_prize_count($mid);
                        
                        //增加不中奖的记录
                        $this->_add_unwin_prize_record($member_info);
                    }
                }
                else
                {
                    //没中奖，直接返回
                    $result['is_prize']=0;
                    $result['prize_msg']="没中奖4";
                    $result['prize_left_count']=$member_info['prize_left_count']-1;
                    
                    //抽奖次数减一
                        $this->_reduce_prize_count($mid);
                        
                        //增加不中奖的记录
                        $this->_add_unwin_prize_record($member_info);
                }
                
                
            }
            
          
            

            $this->json_output($result);  
        
    }
    
    
    /*
     * 减少抽奖的次数
     */
    private function _reduce_prize_count($mid)
    {
        M("acshenzhen_member_info")->where(array('mid'=>$mid))->setDec("prize_left_count");
    }
    
    /*
     * 增加不中奖的记录
     */
    private function _add_unwin_prize_record($member_info) {
        $data['mid']=$member_info['mid'];
        $data['pid']=0;
        $data['ctime']=I("server.REQUEST_TIME");
        $data['schoolid']=$member_info['schoolid'];
        $data['grade_id']=$member_info['grade_id'];
        $data['class_id']=$member_info['class_id'];
        
        M("acshenzhen_prize_record")->add($data);
        
        
    }
    
    
    /*
     * 统一输出的格式
     */
    public function json_output($data,$suc_msg="OK",$err_msg="NO",$more_data) {
        if(!empty($data))
        {
            $res['err']=0;
            $res['msg']=$suc_msg;
            $res['count']=count($data);

            $res['content']=$data;
            
            
            
        }
        else
        {
            $res['err']=0;
            $res['msg']=$err_msg;
            $res['count']=0;
            $res['content']="";
        }
        if(!empty($more_data))
        {
            $res['more_data']=$more_data;
        }
        
        echo json_encode($res);
    }
  
}